package role

import (
	"sanguo/cluster"
	"sanguo/node/common/aoi"
	"sanguo/node/node_map"
	"sanguo/node/node_map/scene"
	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/enterMap"

	"github.com/golang/protobuf/proto"
)

type EnterMap struct {
}

func (this *EnterMap) OnCall(replyer *enterMap.EnterMapReplyer, arg *ss_rpc.EnterMapReq) {

	node_map.Debugln("OnCall EnterMap", arg)

	scene_ := scene.GetSceneByType(scene.SceneType(arg.GetMapType()))

	if nil == scene_ {

		node_map.Debugln("OnCall EnterMap", arg.GetMapType(), "not found")

		replyer.Reply(&ss_rpc.EnterMapResp{
			Ok: proto.Int32(0),
		})
		return
	}

	scene_.PostTask(func() {
		sceneO := scene_.GetObjByID(arg.GetUserID())
		var r *Role
		var ok bool

		if nil != sceneO {
			scene_.LeaveScene(sceneO)
		}

		r = &Role{}
		r.ID = arg.GetID()
		r.UserID = arg.GetUserID()
		r.Lev = arg.GetLev()
		r.Name = arg.GetName()
		r.Outline = arg.GetOutline()
		r.Portrait = arg.GetPortrait()
		r.Face = arg.GetFace()
		r.Hair = arg.GetHair()
		r.HairColor = arg.GetHairColor()
		r.EyeColor = arg.GetEyeColor()
		r.Cloth = arg.GetCloth()
		r.ClothColor = arg.GetClothColor()
		r.Game = cluster.PeerID(arg.GetGame())
		r.Weapon1 = arg.GetWeapon1()
		r.Weapon2 = arg.GetWeapon2()
		r.ScenePos = scene.Position{
			X:     arg.GetPos().GetX(),
			Y:     arg.GetPos().GetY(),
			Z:     arg.GetPos().GetZ(),
			Angle: arg.GetAngle(),
		}
		r.LastPos = r.ScenePos
		r.Observers = map[aoi.AOIObject]bool{}
		r.enter = map[*Role]bool{}
		r.leave = map[*Role]bool{}
		r.StoryStage = arg.GetStoryStage()

		ok = scene_.EnterScene(r, aoi.Position{
			X: r.AoiPos.X,
			Y: r.AoiPos.Y,
		})

		resp := &ss_rpc.EnterMapResp{}
		if ok {
			resp.Ok = proto.Int32(1)
		} else {
			resp.Ok = proto.Int32(0)
		}
		replyer.Reply(resp)
	})
}

/*
func onStartAoi(session kendynet.StreamSession, msg proto.Message) {
	req := msg.(*ss_message.StartAoi)

	scene_ := scene.GetSceneByType(scene.SceneType(req.GetMapType()))
	if nil == scene_ {
		return
	}

	scene_.PostTask(func() {
		sceneO := scene_.GetObjByID(req.GetUserID())
		scene_.StartAoi(sceneO)
	})
}*/

func init() {
	enterMap.Register(&EnterMap{})
	//cluster.Register(&ss_message.StartAoi{}, onStartAoi)
}
